package org.qydjk.console.controller.seller;

import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.user.User;
import org.qydjk.common.pojo.seller.*;
import org.qydjk.common.shiro.vo.ShiroUser;
import org.qydjk.common.util.ListUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.common.vo.autocomplete.AutoCompleteBean;
import org.qydjk.common.vo.autocomplete.AutoCompleteResponse;
import org.qydjk.common.vo.ext.SellerLogEnum;
import org.qydjk.console.service.ICategoryService;
import org.qydjk.console.service.ISellerService;
import org.qydjk.console.vo.SellerExtendBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 商家管理
 * Created by Edward_yang on 2017/12/14 0014.
 */
@Controller
@RequestMapping("/seller")
public class SellerController extends BaseController {
    @Autowired
    private ISellerService sellerService;
    @Autowired
    private ICategoryService categoryService;

    /***
     * 商家管理跳转
     * @author Edward_yang
     * @uptime 2017-12-14
     * @return
     */
    @RequestMapping("/gotoSellerInfo.do")
    public String gotoSellerInfo() {
        return "seller/sellerInfo";
    }


    /***
     * 商家列表数据
     * @author Edward_yang
     * @uptime 2017-12-14
     * @return
     */
    @RequestMapping("/sellerList.do")
    @ResponseBody
    public Object sellerList(Integer page, Integer rows, String phone, String sellerName, String verifyType, String status, String cityid, String classifyid, String labelid) {
        HibernatePage pager = new HibernatePage(page, rows);
        String sql = "SELECT qs.id as id ,qu.phone as userZH, qs.name as sellerName, qs.logo as sellerLogo ,qs.verify_type as verifyType ,qs.status as status,qs.tel as tel,qs.address as address ,qs.virtaul_comment_count as virtaulCommentCount ,qs.comment_count as commentCount, qs.comment_score as commentScore ,qs.virtual_appointment_count as virtualAppointmentCount , qs.create_time as createDate , " +
                "  qs.settlement_ratio as settlementRatio,qs.virtual_collect_account  as virtualCollectAccount ,qs.appointment_count  as appointmentCount,qs.collect_account  as collectAccount ,qs.ord as ord,qs.product_count as productCount , qs.initiate_price as initiatePrice" +
                "  From qy_seller qs, qy_user qu " +
                "  where qs.user_id=qu.id";
        String sqlCount = "SELECT count(qs.id) " +
                "  From qy_seller qs, qy_user qu " +
                "  where qs.user_id=qu.id";
        if (!StringUtil.isEmptyOrNull(phone)) {
            sql += " and qu.phone=" + phone;
            sqlCount += " and qu.phone=" + phone;
        }
        if (!StringUtil.isEmptyOrNull(sellerName)) {

            sql += " and qs.name like'%" + sellerName + "%'";
            sqlCount += " and qs.name like'%" + sellerName + "%'";
        }
        if (!StringUtil.isEmptyOrNull(verifyType)) {
            if (!"-1".equals(verifyType)) {
                sql += " and qs.verify_type=" + verifyType;
                sqlCount += " and qs.verify_type=" + verifyType;
            }
        }
        if (!StringUtil.isEmptyOrNull(status)) {
            if (!"-1".equals(status)) {
                sql += " and qs.status=" + status;
                sqlCount += " and qs.status=" + status;
            }
        }
        //城市
        if (!StringUtil.isEmptyOrNull(cityid)) {
            if (!"-1".equals(cityid)) {
                String cityidSting=StringUtil.dotAddStartEnd(cityid);
                sql += " and qs.area_ids  like'%" + cityidSting + "%'";
                sqlCount += " and qs.area_ids  like'%" + cityidSting + "%'";
            }
        }
        //分类
        if (!StringUtil.isEmptyOrNull(classifyid)) {
            if (!"-1".equals(classifyid)) {
                String classifyidSting=StringUtil.dotAddStartEnd(classifyid);
                sql += " and qs.category_ids  like'%" + classifyidSting + "%'";
                sqlCount += " and qs.category_ids  like'%" + classifyidSting + "%'";
            }
        }
        //标签
        if (!StringUtil.isEmptyOrNull(labelid)) {
            if (!"-1".equals(labelid)) {
                String labelidSting=StringUtil.dotAddStartEnd(labelid);
                sql += " and qs.label_codes  like'%" + labelidSting + "%'";
                sqlCount += " and qs.label_codes  like'%" + labelidSting + "%'";
            }
        }
        sql += " ORDER BY  qs.ord desc";
        try {
            List<Map<String, Object>> sellerList = baseService.findMapBySQL(sql, pager);
            int total = baseService.getRecordCountSQL(sqlCount);

            return new EasyUIResponse(total, sellerList);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /***
     * 添加页面
     * @author Edward_yang
     * @uptime 2017-12-15
     * @return
     */
    @RequestMapping("/gotoAddSeller.do")
    public String gotoAddSeller() {
        return "seller/seller_add";
    }

    /***
     * 编辑页面
     * @author Edward_yang
     * @uptime 2017-12-20
     * @return
     */
    @RequestMapping("/gotoEditSeller.do")
    public String gotoEditSeller(Integer sellerId) {
        System.out.println("商家ID:" + sellerId);
        try {
            Seller seller = baseService.get(Seller.class, sellerId);

            //逗号处理
            String leafCatIds = categoryService.findAllNoParentCatIds(StringUtil.dotWipeStartEnd(seller.getCategoryIds()));
            seller.setCategoryIds(leafCatIds);
            seller.setAreaIds(StringUtil.dotWipeStartEnd(seller.getAreaIds()));
            seller.setCategoryIds(StringUtil.dotWipeStartEnd(seller.getCategoryIds()));

            User user = baseService.get(User.class, seller.getUserId());
            request.setAttribute("seller", seller);
            request.setAttribute("userPhone", user.getPhone());
            List<SellerImgs> SellerImgsList = baseService.findBeanBySQL(" select * from qy_seller_imgs where seller_id=" + seller.getId(), SellerImgs.class);
            String imgsString = "";
            for (SellerImgs imgs : SellerImgsList) {
                imgsString += imgs.getImg() + ",";
            }
            request.setAttribute("imgsString", imgsString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "seller/seller_edit";
    }

    /***
     * 商家添加
     * @author Edward_yang
     * @uptime 2017-12-14
     */
    @RequestMapping("/add.do")
    @ResponseBody
    public Object addSeller(SellerExtendBean sellerExtendBean) {
        ShiroUser shiroUser = getShiroUser();
        if (sellerExtendBean.getUserId() == null) {
            return renderError("请填写注册的用户账号");
        }
        try {
            String[] categoryIdsArr = request.getParameterValues("categoryIds");
            String categoryIds = ListUtil.arrToString(categoryIdsArr);
            String catids = categoryService.findAllByLeafIds(categoryIds);
            sellerExtendBean.setCategoryIds(catids);
            Boolean ss = sellerService.addSellerALlInfo(sellerExtendBean, shiroUser, request);
            if (ss) {
                return renderSuccess();
            } else {
                return renderError("添加数据存在问题");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }


    /***
     * 商家修改
     * @author Edward_yang
     * @uptime 2017-12-20
     */
    @RequestMapping("/edit.do")
    @ResponseBody
    public Object editSeller(SellerExtendBean sellerExtendBean) {
        ShiroUser shiroUser = getShiroUser();
        if (sellerExtendBean.getUserId() == null) {
            return renderError("请填写注册的用户账号");
        }
        try {
            String[] categoryIdsArr = request.getParameterValues("categoryIds");
            String categoryIds = ListUtil.arrToString(categoryIdsArr);
            String catids = categoryService.findAllByLeafIds(categoryIds);
            sellerExtendBean.setCategoryIds(catids);
            Boolean ss = sellerService.updateSellerALlInfo(sellerExtendBean, shiroUser, request);
            if (ss) {
                return renderSuccess();
            } else {
                return renderError("修改数据存在问题");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }

    }


    /***
     * 商家删除
     * @author Edward_yang
     * @uptime 2017-12-14
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object deleteSeller(Integer sellerId) {
        ShiroUser shiroUser = getShiroUser();
        try {
            Seller seller = baseService.get(Seller.class, sellerId);
            baseService.delete(seller);
            //日志
            SellerLog sellerLog = new SellerLog();
            sellerLog.setSellerId(seller.getId());//商家id
            sellerLog.setUserId(shiroUser.getId()); //管理员id
            sellerLog.setUsername(shiroUser.getName());//管理员名称
            sellerLog.setType(SellerLogEnum.DELETE.getType()); //状态:删除
            sellerLog.setTypeName(SellerLogEnum.DELETE.getTypeName());//名称
            sellerLog.setCreateTime(new Date());
            sellerLog.setUpdateTime(new Date());
            baseService.save(sellerLog);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /****
     * 跳转商家审核
     * @author Edward_yang
     * @uptime 2017-12-18
     * @return
     */
    @RequestMapping("/gotoCheckSeller.do")
    public String gotoCheckSeller(Integer sellerId) {
        try {
            Seller seller = baseService.get(Seller.class, sellerId);
            request.setAttribute("seller", seller);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "seller/seller_checkSeller";
    }

    /***
     *商家审核
     * @author Edward_yang
     * @uptime 2017-12-14
     */
    @RequestMapping("/checkSeller.do")
    @ResponseBody
    public Object checkSeller(Integer sellerId, Integer sellerType) {
        ShiroUser shiroUser = getShiroUser();
        try {
            Seller seller = baseService.get(Seller.class, sellerId);

            seller.setVerifyType(sellerType);
            seller.setUpdateTime(new Date());
            baseService.saveOrUpdate(seller);
            //日志
            SellerLog sellerLog = new SellerLog();
            sellerLog.setSellerId(seller.getId());//商家id
            sellerLog.setUserId(shiroUser.getId()); //管理员id
            sellerLog.setUsername(shiroUser.getName());//管理员名称
            sellerLog.setType(SellerLogEnum.VERIFY.getType()); //状态:审核
            sellerLog.setTypeName(SellerLogEnum.VERIFY.getTypeName());//名称
            sellerLog.setCreateTime(new Date());
            sellerLog.setUpdateTime(new Date());
            baseService.save(sellerLog);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }


    /****
     * 跳转商家启用和禁用
     * @author Edward_yang
     * @uptime 2017-12-18
     * @return
     */
    @RequestMapping("/gotoCheckStauteSeller.do")
    public String gotoCheckStauteSeller(Integer sellerId) {
        try {
            Seller seller = baseService.get(Seller.class, sellerId);
            request.setAttribute("seller", seller);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "seller/seller_checkStauteSeller";
    }

    /***
     *商家启用和禁用
     * @author Edward_yang
     * @uptime 2017-12-15
     */
    @RequestMapping("/checkStauteSeller.do")
    @ResponseBody
    public Object checkStauteSeller(Integer sellerId, Integer status) {

        try {
            Seller seller = baseService.get(Seller.class, sellerId);
            seller.setStatus(status);
            seller.setUpdateTime(new Date());
            baseService.saveOrUpdate(seller);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /****
     * 跳转商家启用和禁用
     * @author Edward_yang
     * @uptime 2017-12-18
     * @return
     */
    @RequestMapping("/gotoCheckSellerAccountRatio.do")
    public String gotoCheckSellerAccountRatio(Integer sellerId) {
        try {
            Seller seller = baseService.get(Seller.class, sellerId);
            request.setAttribute("seller", seller);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "seller/seller_checkSellerAccountRatio";
    }


    /***
     *商家修改结算比例
     * @author Edward_yang
     * @uptime 2017-12-15
     */
    @RequestMapping("/checkSellerAccountRatio.do")
    @ResponseBody
    public Object checkSellerAccountRatio(Integer sellerId, BigDecimal settlementRatio) {
        ShiroUser shiroUser = getShiroUser();
        try {
            Seller seller = baseService.get(Seller.class, sellerId);
            seller.setSettlementRatio(settlementRatio);
            seller.setUpdateTime(new Date());
            baseService.saveOrUpdate(seller);
            //日志
            SellerLog sellerLog = new SellerLog();
            sellerLog.setSellerId(seller.getId());//商家id
            sellerLog.setUserId(shiroUser.getId()); //管理员id
            sellerLog.setUsername(shiroUser.getName());//管理员名称
            sellerLog.setType(SellerLogEnum.RATIO.getType()); //状态:修改结算比例
            sellerLog.setTypeName(SellerLogEnum.RATIO.getTypeName());//名称
            sellerLog.setCreateTime(new Date());
            sellerLog.setUpdateTime(new Date());
            baseService.save(sellerLog);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }


    /**
     * 自动补全 商家用户信息
     *
     * @author Edward_yang
     * @uptime 2017-12-20
     */
    @RequestMapping("/autoCompleteData.do")
    @ResponseBody
    public Object sellerUserAutoCompleteData() {
        List<AutoCompleteBean> list = new ArrayList<AutoCompleteBean>();
        String query = request.getParameter("query");
        if (StringUtil.isEmptyOrNull(query)) {
            return new AutoCompleteResponse(list);
        }
         String sql = "SELECT name as `value`,concat(id,'') AS `data` FROM qy_seller WHERE status=1 and verify_type=1 and name LIKE '%"+ query +"%'";

        try {
            list = baseService.findBeanBySQL(sql, AutoCompleteBean.class, new HibernatePage(1, 10));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AutoCompleteResponse(list);
    }

    /****
     * 校验用户账号是否使用
     * @author Edward_yang
     * @uptime 2017-12-20
     * @param phone
     * @return
     */
    @RequestMapping("/querysellerUser.do")
    @ResponseBody
    public Object querSellerUser(String phone) {

        try {
            User user = baseService.findSingleBeanBySQL("SELECT * FROM  qy_user where phone=" + phone, User.class);
            if (user == null) {
                return renderError("请注册该账号");
            }
            List<Map<String, Object>> sellerList = baseService.findMapBySQL("SELECT qu.phone FROM qy_seller qs , qy_user qu  WHERE qs.user_id=qu.id  and qu.phone=" + phone);
            if (sellerList.size() > 0) {
                return renderError("该账号已经注册商家");
            } else {
                return renderSuccess("可以使用该账号");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }

    }

    /***
     * 编辑服务标签
     * @author Edward_yang
     * @uptime 2017-12-22
     * @return
     */
    @RequestMapping("/gotoEditSellerServeLabel.do")
    public String gotoEditSellerServeLabel(Integer sellerId) {
        try {
            Seller seller = baseService.get(Seller.class, sellerId);
            //全部服务标签
            List<Map<String, Object>> serveLabelList = baseService.findMapBySQL("SELECT qsl.ord as ord ,qsl.id as id ,qsl.class_property_text as name FROM  qy_serve_label qsl");
            //商家勾选服务标签
            String sql = "SELECT concat(qssl.serve_label_id,'_',qssl.ord) AS X  FROM qy_seller_serve_label qssl WHERE qssl.seller_id=" + sellerId;
            List<Object> SellerserveLabelList = baseService.findSingleColumnListBySQL(sql);
            request.setAttribute("serveLabelList", serveLabelList);
            request.setAttribute("sellerserveLabelList", SellerserveLabelList);
            request.setAttribute("seller", seller);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "seller/seller_editServeLabel";
    }

    /***
     * 保存商家服务标签
     * @author Edward_yang
     * @uptime 2017-12-26
     * @param sellerId
     * @param serveLabelList
     * @return
     */
    @RequestMapping("/editSellerServeLabel.do")
    @ResponseBody
    public Object editSellerServeLabel(String serveLabelList, Integer sellerId) {
        try {
            baseService.excuteSQL("DELETE FROM qy_seller_serve_label WHERE seller_id =" + sellerId);//商家服务标签
            String[] serveLabelLists = serveLabelList.split(",");
            for (int i = 0, len = serveLabelLists.length; i < len; i++) {
                String[] serveLabelListss = serveLabelLists[i].toString().split("_");
                System.out.println(serveLabelListss[0].toString());
                System.out.println(serveLabelListss[1].toString());
                SellerServeLabel sellerServeLabel = new SellerServeLabel();
                sellerServeLabel.setSellerId(sellerId);
                sellerServeLabel.setCreateTime(new Date());
                sellerServeLabel.setUpdateTime(new Date());
                sellerServeLabel.setServeLabelId(Integer.valueOf(serveLabelListss[0].toString()));
                sellerServeLabel.setOrd(Integer.valueOf(serveLabelListss[1].toString()));
                baseService.save(sellerServeLabel);
            }
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /***
     *通过商家ids查询
     * @param areaIds
     * @return
     */
    @RequestMapping("/findSellerCity.do")
    @ResponseBody
    public Object findSellerCity(String areaIds) {
        String areaIdss=StringUtil.dotWipeStartEnd(areaIds);
        try {
                String sql="SELECT qa.id as id ,qa.name as name,qa.level as level FROM qy_area qa WHERE qa.id in ("+areaIdss+")";
                List<Map<String,Object>> sellerAreaList=baseService.findMapBySQL(sql);
            return renderSuccess(sellerAreaList);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

}
